/**
 * 需要知道自己动画 animationClip
 * 需要播放动画的能力 - animationComponent
 */
import { AnimationClip, animation, Sprite } from "cc";
import {TILE_HEIGHT, TILE_WIDTH} from "../Scripts/Tile/TileManager";
import ResourceManager from "../Runtime/ResourceManager";
import {StateMachine} from "./StateMachine";

const ANIMATION_SEED = 1/8;

export default class State {

    animationClip: AnimationClip;
    constructor(private fsm: StateMachine,
                private path: string,
                private wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal) {
        this.init();
    }

    async init() {
        // 关键帧列表
        const promise = ResourceManager.Instance.loadDir(this.path);
        this.fsm.waitingList.push(promise);
        const spriteFrames = await promise;
        this.animationClip = new AnimationClip();

        const track  = new animation.ObjectTrack(); // 创建一个向量轨道
        track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame'); // 指定轨道路径，即指定目标对象为 "Foo" 子节点的 "position" 属性
        const frames = spriteFrames.map((item,index) => [ANIMATION_SEED * index, item]);
        track.channel.curve.assignSorted(frames);

        this.animationClip.duration = ANIMATION_SEED * frames.length; // 整个动画剪辑的周期
        this.animationClip.wrapMode = this.wrapMode;
        this.animationClip.name = this.path;
        // 最后将轨道添加到动画剪辑以应用
        this.animationClip.addTrack(track);
    }

    run() {
        this.fsm.animationComponent.defaultClip = this.animationClip;
        this.fsm.animationComponent.play();
    }

}